﻿using System.Collections.Generic;
using System.Linq;
using Fabrication.Exceptions;

namespace Fabrication.ValueProviders
{
    internal class DistinctValueProvider<T> : ValueProviderBase<T>, IResettableProvider
    {
        private readonly List<T> originalValues;
        private List<T> values;
        private readonly int originalCount;

        public DistinctValueProvider(IEnumerable<T> values)
        {
            originalValues = values.ToList();
            originalCount = originalValues.Count;

            Reset();
        }

        // TODO: Find out why we can't access Property here (i.e. why it wasn't initialized)
        protected override T GetValue(object item)
        {
            if (values.Count == 0)
                throw new ValueProviderException(string.Format("Cannot populate property '{0}' as there are only {1} distinct values", "Unknown", originalCount));

            var index = RandomNumberGenerator.GetInteger(0, values.Count() - 1);
            var value = values.ElementAt(index);
            values.RemoveAt(index);
            return value;
        }

        public void Reset()
        {
            values = new List<T>(originalValues);
        }
    }

    internal interface IResettableProvider
    {
        void Reset();
    }
}